// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database();
const _ = db.command;
const $ = db.command.aggregate;

var return_msg = [];
// 云函数入口函数
exports.main = async (event, wxContext) => {
  try{
      //统计指定时间段的销售明细
      if(event.tongji){
        var price_count = await db.collection('pay_count').aggregate()
        .match({
          user_id:event.user_id,
          date: _.gte(event.strat).and(_.lte(event.end))
        })
        .group({
          _id: null,
          sale_Price: $.sum('$Price'),
        }).end()
        var money_count = await db.collection('pay_count').aggregate()
        .match({
          pay_lx:0,
          user_id:event.user_id,
          date: _.gte(event.strat).and(_.lte(event.end))
        })
        .group({
          _id: null,
          sale_Price: $.sum('$Price'),
        })
        .end()
        var card_count = await db.collection('pay_count').aggregate()
        .match({
          pay_lx:1,
          user_id:event.user_id,
          date: _.gte(event.strat).and(_.lte(event.end))
        })
        .group({
          _id: null,
          sale_Price: $.sum('$Price'),
        })
        .end()
        var wechat_count = await db.collection('pay_count').aggregate()
        .match({
          pay_lx:3,
          user_id:event.user_id,
          date: _.gte(event.strat).and(_.lte(event.end))
        })
        .group({
          _id: null,
          sale_Price: $.sum('$Price'),
        })
        .end()
        var alipay_count = await db.collection('pay_count').aggregate()
        .match({
          pay_lx:2,
          user_id:event.user_id,
          date: _.gte(event.strat).and(_.lte(event.end))
        })
        .group({
          _id: null,
          sale_Price: $.sum('$Price'),
        })
        .end()
        var sale_count = await db.collection('pay_count')
        .where({
          user_id:event.user_id,
          date: _.gte(event.strat).and(_.lte(event.end))
        }).count()
        var sale_count2 = await db.collection('pay_count').aggregate()
        .match({
          user_id:event.user_id,
          date: _.gte(event.strat).and(_.lte(event.end))
        })
        .group({
          _id: null,
          sale_num: $.sum('$price_num'),
        }).end()
        return_msg = {
        "error":'0',
        "price_count":price_count,
        "sale_count":sale_count,
        "money_count":money_count,
        "card_count":card_count,
        "wechat_count":wechat_count,
        "alipay_count":alipay_count,
        "sale_count2":sale_count2,
        }
      }
  }catch(e){
    return_msg = {"error":"1","msg":"未知异常:" + e}
  }
  return return_msg;
}